package com.doge.calcalbum.business.vip

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.webkit.WebView
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import com.doge.calcalbum.R
import com.doge.calcalbum.analysis.analysisEvent
import com.doge.calcalbum.analysis.page_vip
import com.doge.calcalbum.analysis.product
import com.doge.calcalbum.api.model.DiscountInfo
import com.doge.calcalbum.api.model.OrderInfo
import com.doge.calcalbum.api.model.ProductInfo
import com.doge.calcalbum.business.WebActivity
import com.doge.calcalbum.business.account.AppUserViewModel
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.core.base.appViewModels
import com.doge.calcalbum.core.base.isRefreshing
import com.doge.calcalbum.databinding.ActivityVipBuy2Binding
import com.doge.calcalbum.utils.*

class VipBuyActivity : BaseActivity() {
    override val statusBarLightMode = false
    private val binding by lazy { ActivityVipBuy2Binding.inflate(layoutInflater) }
    private val viewModel by appViewModels<VipBuyViewModel>()
    private var webView: WebView? = null
    private var products: List<ProductInfo>? = null
    private var payType: Int = ProductInfo.PAY_TYPE_WECHAT
    private var selected: Int = 1
    private var isCheckPolicy = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        analysisEvent(page_vip)
        systemWindowInsetsTop.observe(this) {
            binding.fitsSys.setPadding(it / 2)
        }
        webView = ViewBuyWebHelper.attach(binding.layWeb)

        val skinViews = arrayOf(
            binding.tip2Image,
            binding.tip2Text,
        )
        skinViews.forEach { it.isVisible = !disableSkin }

        binding.priceDesc13.paintFlags = binding.priceDesc13.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        binding.priceDesc23.paintFlags = binding.priceDesc23.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        binding.priceDesc33.paintFlags = binding.priceDesc33.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        initialViews()
        ViewBuyWebHelper.loading.observe(this) {
            binding.buyLoading.isVisible = it.isRefreshing()
        }
        viewModel.loading.observe(this) {
            binding.loading.isVisible = it.isRefreshing()
        }
        viewModel.discountInfo.observe(this) {
            updateDiscountInfo(it)
        }
        viewModel.productList.observe(this) {
            binding.empty.isVisible = it.isNullOrEmpty()
            products = it
            updateProductInfo()
        }
        viewModel.order.observe(this) {
            updateOrder(it)
        }
        viewModel.request()
    }

    @SuppressLint("SetTextI18n")
    private fun updateProductInfo() {
        val product1 = products?.firstOrNull()
        if (product1 != null) {
            binding.product1.isVisible = true
            binding.desc1.text = product1.description
            binding.priceDesc11.text = product1.priceDesc1
            binding.priceDesc12.text = product1.priceDesc2
            binding.priceDesc13.text = product1.priceDesc3
            binding.hot1.isVisible = product1.hot == 1
            binding.product1.setBackgroundResource(if (selected == 0) R.drawable.shape_pay_vip_selected else R.drawable.shape_pay_vip_normal)
        } else {
            binding.product1.isVisible = false
        }

        val product2 = if ((products?.size ?: 0) > 1) products?.get(1) else null
        if (product2 != null) {
            binding.product2.isVisible = true
            binding.desc2.text = product2.description
            binding.priceDesc21.text = product2.priceDesc1
            binding.priceDesc22.text = product2.priceDesc2
            binding.priceDesc23.text = product2.priceDesc3
            binding.hot2.isVisible = product2.hot == 1
            binding.product2.setBackgroundResource(if (selected == 1) R.drawable.shape_pay_vip_selected else R.drawable.shape_pay_vip_normal)

        } else {
            binding.product2.isVisible = false
        }

        val product3 = if ((products?.size ?: 0) > 2) products?.get(2) else null
        if (product3 != null) {
            binding.product3.isVisible = true
            binding.desc3.text = product3.description
            binding.priceDesc31.text = product3.priceDesc1
            binding.priceDesc32.text = product3.priceDesc2
            binding.priceDesc33.text = product3.priceDesc3
            binding.hot3.isVisible = product3.hot == 1
            binding.product3.setBackgroundResource(if (selected == 2) R.drawable.shape_pay_vip_selected else R.drawable.shape_pay_vip_normal)
        } else {
            binding.product3.isVisible = false
        }
    }

    private fun updateDiscountInfo(data: DiscountInfo?) {
        binding.discount.isVisible = data != null
        if (data == null) return
        binding.discount1.text = data.title
        binding.discount2.text = data.desc

        fun appendZero(value: Long): String {
            return if (value > 9) "$value"
            else "0$value"
        }
        val leftSec = (data.leftTime) / 1000
        val day = leftSec / (3600 * 24)
        val leftHourSec = leftSec - (day * (3600 * 24))
        val hour = leftHourSec / 3600
        val leftMinSec = leftHourSec - (hour * 3600)
        val min = leftMinSec / 60
        val sec = leftMinSec - (min * 60)
        val result = "${appendZero(hour)}:${appendZero(min)}:${appendZero(sec)}"
        binding.discount3.text = result
        binding.discount.alpha = if(leftSec > 0) 1f else 0f // 整条不显示
    }

    private fun initialViews() {
        val agreement = SpannableString(getString(R.string.recharge_agreement))
        agreement.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                WebActivity.start(widget.context, urlVipBuy)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = (0xFF666666).toInt()
                ds.isUnderlineText = false
            }

        }, 7, agreement.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.buyPolicy.text = agreement
        binding.buyPolicy.movementMethod = LinkMovementMethod.getInstance()
        binding.buyPolicy.highlightColor = Color.TRANSPARENT
        updatePayType()

        binding.item1.setOnClickListener {
            selected = 0
            updateProductInfo()
        }
        binding.item2.setOnClickListener {
            selected = 1
            updateProductInfo()
        }
        binding.item3.setOnClickListener {
            selected = 2
            updateProductInfo()
        }
        binding.pageBack.setOnClickCallback {
            finish()
        }
        binding.checkbox.setOnClickListener {
            isCheckPolicy = !isCheckPolicy
            binding.checkboxState.setImageResource(if (isCheckPolicy) R.mipmap.recharge_checkbox_checked
            else R.mipmap.recharge_checkbox_normal)
        }
        binding.payTypeWechat.setOnClickListener {
            payType = ProductInfo.PAY_TYPE_WECHAT
            updatePayType()
        }
        binding.payTypeAlipay.setOnClickListener {
            payType = ProductInfo.PAY_TYPE_ALIPAY
            updatePayType()
        }
        binding.layBuy.setOnClickCallback {
            buy()
        }
    }

    private fun buy() {
        val size = products?.size ?: 0
        if (selected < size) {
            if (isCheckPolicy) {
                analysisEvent("${product}_${products?.get(selected)?.productId}_${payType}")
                viewModel.buy(products?.get(selected), payType)
            } else {
                toast(R.string.recharge_agreement_hint)
            }
        }
    }

    private fun updateOrder(data: OrderInfo?) {
        if (data?.payUrl == null) return
        ViewBuyWebHelper.load(webView, data.payUrl)
    }

    private fun updatePayType() {
        binding.wechatCheckbox.setImageResource(
            if (payType == ProductInfo.PAY_TYPE_WECHAT) R.mipmap.pay_checkbox_checked2 else R.mipmap.pay_checkbox_uncheck2
        )
        binding.payTypeWechat.setBackgroundResource(
            if (payType == ProductInfo.PAY_TYPE_WECHAT) R.drawable.shape_pay_type_selected else R.drawable.shape_pay_type_normal
        )
        binding.alipayCheckbox.setImageResource(
            if (payType == ProductInfo.PAY_TYPE_ALIPAY) R.mipmap.pay_checkbox_checked2 else R.mipmap.pay_checkbox_uncheck2
        )
        binding.payTypeAlipay.setBackgroundResource(
            if (payType == ProductInfo.PAY_TYPE_ALIPAY) R.drawable.shape_pay_type_selected else R.drawable.shape_pay_type_normal
        )
    }

    override fun onResume() {
        super.onResume()
        AppUserViewModel.get().requestSelfInfo()
    }

    override fun finish() {
        super.finish()
        webView?.let { binding.layWeb.removeView(it) }
    }

    companion object {
        fun start(context: Context?) {
            if (context == null) return
            context.startActivity(Intent(context, VipBuyActivity::class.java))
        }
    }
}